package com.dingding.transfer.stamper.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.dingding.transfer.stamper.constant.DingDingUrl;
import com.dingding.transfer.stamper.constant.EventSubscribePara;
import com.dingding.transfer.stamper.constant.StamperPara;
import com.dingding.transfer.stamper.constant.StamperUrl;
import com.dingding.transfer.stamper.dto.BaseResult;
import com.dingding.transfer.stamper.handler.EventHandlerComposite;
import com.dingding.transfer.stamper.service.CallBackService;
import com.dingding.transfer.stamper.util.DingCallbackCrypto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/3/30 11:33
 **/
@Service
@Slf4j
public class CallBackServiceImpl implements CallBackService {
    @Autowired
    private EventHandlerComposite eventHandlerComposite;

    @Autowired
    private EventSubscribePara eventSubscribePara;

    @Autowired
    private StamperPara stamperPara;

    @Cacheable(value = "DINGDING_TOKEN_EXPIRE",key="#p0 + #p1",unless = "#result == null")
    @Override
    public String getToken(String appKey,String appSecret) {
        log.info("获取accessToken+++++++++++");
        StringBuffer buffer = new StringBuffer(DingDingUrl.GET_ACCESS_TOKEN);
        buffer.append("?appkey=").append(appKey);
        buffer.append("&appsecret=").append(appSecret);
        String result = HttpUtil.get(buffer.toString());
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("access_token");
    }

    @Cacheable(value = "STAMPER_TOKEN_EXPIRE",unless = "#result == null")
    public String getStamperToken(){
        Map<String, Object> params = new HashMap<>(2);
        params.put("key", stamperPara.getAppKey());
        params.put("secret", stamperPara.getAppsecret());
        // 请求
        String postResponse = HttpUtil.post(StamperUrl.PATH_T_TOKEN, params);
        // 解析结果
        BaseResult res = JSONObject.parseObject(postResponse, BaseResult.class);
        if (res != null && Objects.equals(res.getCode(), 0)) {
            String token = res.getData().toString();
            return token;
        } else {
            log.error("error:" + res.getMessage());
        }
        return null;
    }

    @Override
    public Map<String, String> callBack(DingCallbackCrypto callbackCrypto,JSONObject eventJson) throws DingCallbackCrypto.DingTalkEncryptException {
        // 根据EventType分类处理
        eventHandlerComposite.handle(eventJson);
        // 返回success的加密数据
        Map<String, String> successMap = callbackCrypto.getEncryptedMap("success");
        return successMap;
    }
}
